package com.xipu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.common.result.R;
import com.xipu.yygh.common.utils.JwtHelper;
import com.xipu.yygh.model.user.UserInfo;
import com.xipu.yygh.user.config.properties.WxProperties;
import com.xipu.yygh.user.service.UserInfoService;
import com.xipu.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * description: 微信登录相关接口
 * @author: gql
 * @date: 2022/05
 */
@RequestMapping("/api/user/wx")
@Controller
public class WeixinApiController {

    /**
     * 用户信息Service
     */
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 生成二维码接口-返回生成二维码需要的值
     * @return r
     */
    @ResponseBody
    @GetMapping("/getLoginParam")
    public R getWxLoginParam() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", WxProperties.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            map.put("redirectUri", URLEncoder.encode(WxProperties.WX_OPEN_REDIRECT_URL, "UTF-8"));
            map.put("state", System.currentTimeMillis() + "");
            return R.ok().data(map);
        } catch (UnsupportedEncodingException e) {
            throw new YyghException(20001, "参数错误");
        }
    }

    /**
     * 获取扫码人信息-(扫码后自动调用)
     * @param code 临时票据
     * @param state 状态
     * @return r
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        // 1.使用临时票据code请求微信固定接口
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(String.valueOf(baseAccessTokenUrl),
                WxProperties.WX_OPEN_APP_ID,
                WxProperties.WX_OPEN_APP_SECRET,
                code);
        try {
            String resultAccessToken = HttpClientUtils.get(accessTokenUrl);
            JSONObject jsonObject = JSONObject.parseObject(resultAccessToken);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            // 2.再使用access_token和openid去请求微信固定接口,获取扫码人信息
            StringBuffer baseUserInfoUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            String userInfoUrl = String.format(String.valueOf(baseUserInfoUrl), access_token, openid);
            String resultUserInfo = HttpClientUtils.get(userInfoUrl);

            // 3.获取扫码人微信信息
            JSONObject jsonObjectUserInfo = JSONObject.parseObject(resultUserInfo);
            String nickname = jsonObjectUserInfo.getString("nickname");

            UserInfo userInfo = this.userInfoService.getUserInfoByOpenId(openid);

            // 4.如果是新用户,将微信信息保存到数据库
            if (StringUtils.isEmpty(userInfo)) {
                userInfo = new UserInfo();
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                this.userInfoService.save(userInfo);
            }
            Map<String, String> map = new HashMap<>();
            // 判断微信号码是否绑定了手机
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", openid);
            } else {
                map.put("openid", "");
            }

            // 将用户姓名传递给前端
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            // 生成Token给前端
            map.put("token", JwtHelper.createToken(userInfo.getId(), name));

            // 重定向到微信url
            StringBuffer resultUrl = new StringBuffer().append("redirect:http://localhost:3000/weixin/callback?token=")
                    .append(map.get("token"))
                    .append("&openid=")
                    .append(map.get("openid"))
                    .append("&name=")
                    .append(URLEncoder.encode(map.get("name"), "utf-8"));
            return String.format(String.valueOf(resultUrl), access_token, openid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}



























